package com.security.frame.token.code.impl;

import com.security.frame.core.ValidateCodeRepository;
import com.security.frame.core.code.ValidateCode;
import com.security.frame.core.enums.ValidateCodeType;
import com.security.frame.core.exception.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

/**
 * todo
 *
 * @author wangjie
 * @version V1.0
 * @date 2019/11/28
 */
@Component
@Slf4j
public class TokenValidateCodeRepository implements ValidateCodeRepository {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
        redisTemplate.opsForValue().set(buildKey(request,type),code,30, TimeUnit.MINUTES);
    }

    private String buildKey(ServletWebRequest request, ValidateCodeType type) {
        String deviceId = "001";//request.getHeader("deviceId");
        if(StringUtils.isBlank(deviceId)){
            log.error("【请在请求头中携带devicId参数】");
            throw new ValidateCodeException("请在请求头中携带devicId参数");
        }
        return "code" + type.toString().toLowerCase() + ":" + deviceId;
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {
        Object value = redisTemplate.opsForValue().get(buildKey(request,type));
        if (null == value){
            return null;
        }
        return (ValidateCode) value;
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType type) {
         redisTemplate.delete(buildKey(request,type));
    }
}
